import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom'
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Radio } from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import { openNotification_util, checkdatavalid_util, fetchsync_util, useCallbackState } from '../util/util.js'
const { Search } = Input;
var storage = window.localStorage;






const Custom_table_hooks = (props) => {
  const history = useHistory();

  const [selectionType, setSelectionType] = useState('checkbox');
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])


  // rowSelection object indicates the need for row selection
  const rowSelection = {
    selectedRowKeys: props.selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      props.handleselectson(selectedRows, selectedRowKeys)

    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };


  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };


  //row双击s
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {
        if (props.sfdoubleclick) {
          storage[props.storagekey] = JSON.stringify(record)
          history.push({ pathname: props.doubleclickroute });
        }
        else;
      }
    }
  };



  const getColumnSearchProps = (dataIndex, title) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 8,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        <Input
          ref={searchInput}
          placeholder={`搜索${title}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#a91f24' : undefined,
        }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current ? searchInput.current.select() : 1, 100);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: '#a91f24',
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });


  const colnumsorigin = props.tablecolnum

  const columns = colnumsorigin.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      key: item.key,
      ...getColumnSearchProps(item.key, item.title),
      sorter: (a, b) => a[item.key] > b[item.key],
      sortDirections: ['descend', 'ascend'],
    }
  })
  //console.log(columns)





  return (
    <div style={{ position: "relative", height: "100%", width: props.width ? props.width : "100%" }}>
      <Radio.Group style={{ display: props.ifhiddencchangeselecttype ? "none" : "block" }}
        onChange={({ target: { value } }) => {
          setSelectionType(value);
        }}
        value={selectionType}
      >
        <Radio value="checkbox">多选</Radio>
        <Radio value="radio">单选</Radio>
      </Radio.Group>

      <Table columns={columns} dataSource={props.tabledata} style={{ width: "99%", height: "98%" }}
        onRow={onRowSelect}
        pagination={{ defaultPageSize: 15, total: props.tabledata.length, pageSizeOptions: ['15', '30', '50', '100'] }}

        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        className="custom-table-styles" />
    </div>)

}


export default Custom_table_hooks




var styles = {
  maincontainer: { height: "90%", width: "99%", backgroundColor: `#F1F1F1`, }
}



